package _interview150;

/**
 * 63. 不同路径 II
 */
public class No63 {
    private int[][] obstacleGrid;
    private int[][] cache;

    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        this.obstacleGrid = obstacleGrid;
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        cache = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                cache[i][j] = -1;
            }
        }
        return dfs(m - 1, n - 1);
    }

    private int dfs(int i, int j) {
        if (i < 0 || j < 0 || obstacleGrid[i][j] == 1) return 0;
        else if (i == 0 && j == 0) return 1;
        else if (cache[i][j] != -1) return cache[i][j];
        else return cache[i][j] = dfs(i - 1, j) + dfs(i, j - 1);
    }
}
